package com.laboratory.eventlistenerlearning.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.SimpleApplicationEventMulticaster;

import java.util.concurrent.Executor;

@Configuration
public class EventConfig {

    /**
     * 创建一个异步事件广播器：事件的专属异步实现方法
     * 对于事件异步可以通过在对应的方法上添加@Async注解，或者在方法上添加@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
     * 如果不使用@Async注解，则事件会默认同步执行，通过配置异步事件广播器可以在不使用@Async注解的情况下，将事件异步执行
     *
     * @param executor
     * @return
     */
    @Bean
    public SimpleApplicationEventMulticaster simpleApplicationEventMulticaster(@Qualifier("asyncExecutor") Executor executor) {
        SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(executor);
        eventMulticaster.setErrorHandler(Throwable::printStackTrace);
        return eventMulticaster;
    }

}
